package com.jia.lidao.others;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.jia.lidao.R;
import com.jia.lidao.RunningContext;
import com.jia.lidao.UserUtils;
import com.jia.lidao.others.adapter.AddressAdapter;
import com.jia.lidao.others.adapter.QuickAdapter;
import com.jia.lidao.others.enity.Address;
import com.jia.lidao.others.enity.ModelBeen;
import com.jia.lidao.others.enity.ObjectCallBack;
import com.jia.lidao.others.ui.AddNewAddressActivity;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import okhttp3.Call;


public class AddressFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recyclerView)
    LFRecyclerView recyclerView;
    @BindView(R.id.loading)
    ProgressBar loading;
    @BindView(R.id.tv_add_new_address)
    TextView tvAddNewAddress;
    private int page = 1;
    private List<Address.AddressesBean.DataBean> dataBeen;
    private AddressAdapter addressAdapter;

    private int type=0;

    @Override
    protected int getInflateLayout() {
        return R.layout.address_fragment_layout;
    }

    @Override
    protected void setUpView(View view) {
        tvTitle.setText("收货地址");
        dataBeen = new ArrayList<>();
        addressAdapter = new AddressAdapter(type);
        addressAdapter.setData(dataBeen);

        recyclerView.setRefresh(true);
        recyclerView.setAutoLoadMore(true);
        recyclerView.setNoDateShow();
        recyclerView.setAdapter(addressAdapter);
        recyclerView.setLFRecyclerViewListener(new LFRecyclerView.LFRecyclerViewListener(){
            @Override
            public void onRefresh() {
                queryAddressData(true);
            }

            @Override
            public void onLoadMore() {
                queryAddressData(false);
            }
        });

        addressAdapter.setOnDefaultClickListener(new AddressAdapter.OnDefaultClickListener(){
            @Override
            public void listener(Address.AddressesBean.DataBean itemData, int position, Boolean isDefault) {
                if(isDefault){
                    setDefaultAddress(itemData,position);
                }
            }
        });

        addressAdapter.setOnEditListener(new AddressAdapter.OnEditListener(){
            @Override
            public void listener(Address.AddressesBean.DataBean itemData, int position) {
                    Intent intent = new Intent(getContext(), AddNewAddressActivity.class);
                    intent.putExtra("ID",itemData.getAddress_id());
                    startActivity(intent);
            }
        });

        addressAdapter.setOnDeletListener(new AddressAdapter.OnDeletListener(){
            @Override
            public void listener(Address.AddressesBean.DataBean itemData, int position) {
                showDialog(itemData.getAddress_id(),position);
            }
        });
        addressAdapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<Address.AddressesBean.DataBean>(){
            @Override
            public void OnItemClick(Address.AddressesBean.DataBean data, int postion) {
                if(type==0) {
                    Log.e("HQQ", "OnItemClick: " + data.getAddress_id());
                    Intent intent = new Intent();
                    intent.putExtra("Address", data);
                    getActivity().setResult(Activity.RESULT_OK, intent);
                    getActivity().finish();
                }
            }
        });

        queryAddressData(true);
    }


    private void queryAddressData(final Boolean isReflush) {
        if (isReflush) {
            page = 1;
        }
        loading.setVisibility(View.VISIBLE);
        String url = API.MEMBER_ADDRESSES + "page=" + page + "&page_size=10&access_token=" + UserUtils.getInstance().getAuthor().access_token;

        TypeToken<Address> typeToken = new TypeToken<Address>() {
        };
        OkHttpUtils.get().url(url).build().execute(new ObjectCallBack<Address>(typeToken) {

            @Override
            public void onError(Call call, Exception e, int id) {

                if (null != recyclerView) {
                    recyclerView.stopRefresh(false);
                    recyclerView.stopLoadMore();
                }
                if (null != loading) {
                    loading.setVisibility(View.GONE);
                }
            }


            @Override
            public void onResponse(Address response, int id) {

                if (isReflush) {
                    dataBeen.clear();
                }
                if (null != response) {
                    if (response.getErr_code() == 0) {
                        Address.AddressesBean addressesBean = response.getAddresses();
                        List<Address.AddressesBean.DataBean> dataBeen = addressesBean.getData();
                        if (null != dataBeen && !dataBeen.isEmpty()) {
                            AddressFragment.this.dataBeen.addAll(dataBeen);
                            ++page;
                        }
//                        if(null!=dataBeen&&dataBeen.size()<10){
//                            recyclerView.
//                        }
                    } else {
                        showToast(response.getErr_msg());
                    }
                }
                addressAdapter.reflashData(dataBeen);
                if (null != recyclerView) {
                    recyclerView.stopRefresh(true);
                    recyclerView.stopLoadMore();
                }
                if (null != loading) {
                    loading.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick(R.id.ib_back)
    public void onClick() {
        getActivity().finish();
    }

    @OnClick(R.id.tv_add_new_address)
    public void onClickAddNewAddress() {
        Intent intent = new Intent(getContext(),AddNewAddressActivity.class);
        startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type=getActivity().getIntent().getIntExtra("type",0);
    }

    private void setDefaultAddress(final Address.AddressesBean.DataBean itemData, final int position){
            String url = API.MEMBER_ADDRESSES_DEFAULT +
                    itemData.getAddress_id()+"/default?access_token="+ UserUtils.getInstance().getAuthor().access_token;
        loading.setVisibility(View.VISIBLE);

        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("Accept","*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>(){};
        OkHttpUtils.post().url(url).headers(hashMap).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != loading) {
                    loading.setVisibility(View.GONE);
                }
            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                if(null != response){
                    if(response.err_code == 0){
                        showToast("设置成功！");
                        for(Address.AddressesBean.DataBean dataBean :dataBeen){
                            if(dataBean.getAddress_id() == itemData.getAddress_id()){
                                dataBean.setIs_default(1);
                            }else {
                                dataBean.setIs_default(0);
                            }
                        }

                        addressAdapter.reflashData(dataBeen);
                    }else {
                        showToast(response.err_msg);
                    }
                }

                if (null != loading) {
                    loading.setVisibility(View.GONE);
                }
            }
        });
    }


    private void delete(int id,final int postion){
        String url = API.MEMBER_ADDRESSES_DELETE+id+"/delete?access_token="+UserUtils.getInstance().getAuthor().access_token;
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("Accept","*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>(){};
        OkHttpUtils.post().url(url).headers(hashMap).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                if(null != response){
                    if(response.err_code == 0){
                        showToast("删除成功！");

                        dataBeen.remove(postion);
                        addressAdapter.notifyItemRemoved(postion);
                        if(postion != dataBeen.size()){
                            addressAdapter.notifyItemRangeChanged(postion, dataBeen.size() - postion);
                        }
                    }else {
                        showToast(response.err_msg);
                    }
                }
            }
        });
    }

    private void showDialog(final  int id ,final int position){
        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                .setTitle("提示")
                .setMessage("您确定要删除吗？")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        delete(id,position);
                    }
                }).create();
        alertDialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        queryAddressData(true);
    }
}